package com.hnust.controller;

import com.hnust.domain.request.ChangePasswordBody;
import com.hnust.domain.request.LoginBody;
import com.hnust.domain.request.RegisterBody;
import com.hnust.service.StudentService;
import com.hnust.util.JwtToken;
import com.hnust.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.TreeMap;

@CrossOrigin("*")
@RestController
@RequestMapping
public class LoginController {
	@Autowired
	private StudentService studentService;

	@PostMapping("/register")
	public Result<Map<String,Boolean>> register(
			@RequestBody RegisterBody registerBody
			){
		String account = registerBody.getAccount();
		String alias = registerBody.getAlias();
		String mail = registerBody.getMail();
		String password = registerBody.getPassword();
		String phoneNumber = registerBody.getPhoneNumber();
		String msg = studentService.register(account,alias,mail,password,phoneNumber);
		Map<String, Boolean> data = new TreeMap<>();
		int code = 0;
		if("注册成功".equals(msg)){
			data.put("flag",true);
			code = 1;
		}else{
			data.put("flag",false);
		}
		return new Result<>(code, msg, data);
	}

	@PostMapping("/passwordLogin")
	public Result<Map<String,String>> passwordLogin(@RequestBody LoginBody loginBody) {
		String account = loginBody.getAccount();
		String password = loginBody.getPassword();
		String msg = studentService.login(account, password);
		int code = 1;
		if (msg.contains("错误") || msg.contains("失败")) {
			code = 0;
		}
		if (code == 0) {
			return new Result<>(0, msg, null);
		} else {
			Map<String,String> map = new TreeMap<>();
			map.put("studentID",msg);
			try {
				map.put("token", JwtToken.createToken(msg, password));
			}catch (Exception e) {
				return new Result<>(0, "服务器错误", null);
			}
			return new Result<>(1, "登陆成功", map);
		}
	}

	@PostMapping("/changePassword")
	public Result<Map<String, Boolean>> changePassword(
			@RequestBody ChangePasswordBody requestBody
	){
		String studentID = requestBody.getStudentID();
		String password = requestBody.getPassword();
		String newPassword = requestBody.getNewPassword();
		String token = requestBody.getToken();
		String msg = studentService.changePassword(studentID,newPassword,password,token);
		int code = 0;
		boolean flag = false;
		if("修改成功".equals(msg)){
			code = 1;
			flag = true;
		}
		Map<String,Boolean> data = new TreeMap<>();
		data.put("flag",flag);
		return new Result<>(code, msg, data);
	}

}
